/**
 * Created by Administrator on 2018/4/3.
 */

var answer_log_id = 0;
var jsApiParameters = "";
var challenge_id = 0;

layui.use(['form', 'layer'], function () {
    var form = layui.form
        , layer = layui.layer;


    function initPage() {
        var token = sessionStorage.access_token;
        if(token==null){
            againToken();
            return;
        }
        $('.app-main').height(winH + 'px');
        var vue = new Vue({
            el: '#index_div',
            data: {
                red_envelope_id: 0,  //挑战id
                challenge_detail: {}, //挑战详情
                answer_log_list: {},  //好友答题记录
                next_page: 1,//下一页的页码
                allpage: 1,//总页码，会从后台获取
                page_size: 4, //每页条数
                total_record: 0, //总条数
            },
            watch: {},
            methods: {
                onClosePopupVue: function (e) {
                    onCloseClickPopup(e.currentTarget);
                },
                onStartAnswer: function () { //开始答题
                    $('#start-answer-pop-up').show();
                    $('html,body').addClass('ovfHiden'); //使网页可滚动
                    initPopupHeight();
                },
                onConfirmPay: function () { //确定支付开始答题
                    var data = {
                        token: token,
                        red_envelope_id: this.red_envelope_id
                    };
                    $('#start-answer-pop-up').hide();
                    $('html,body').removeClass('ovfHiden'); //使网页可滚动

                    if (!data.red_envelope_id) {
                        layer.msg('参数有误');
                        return;
                    }
                    var index = layer.msg('确定进行答题？', {
                        time: 20000, //20s后自动关闭
                        btn: ['确定', '取消'],
                        shade: [0.3, '#000'],
                        yes: function () {
                            layer.close(index);
                            $.ajax({
                                type: "post"
                                , url: '/index/pay/ajax_do_answer'
                                , data: data
                                , async: false
                                , success: function (result) {
                                    console.log(result)
                                    //if (result.code == -1) {   //失败
                                    //    layer.msg(result.msg);
                                    //    return;
                                    //}
                                    if (result.code == 0) { //Token失效
                                        againToken();
                                        return;
                                    }
                                    if (result.code == 1) { //成功
                                        answer_log_id = result.data.answer_log_id;
                                        if (!result.data.is_need_pay) {   //不需要支付
                                            window.location.href = '/pages/time.html?answer_log_id=' + answer_log_id+'&challenge_id='+this.challenge_id;;
                                        } else {
                                            jsApiParameters = JSON.parse(result.data.jsApiParameters);
                                            docallpay();
                                        }
                                    }
                                }
                                , error: function (resq) {
                                    console.info(resq);
                                    layer.msg("服务器异常");
                                }
                            });
                        }
                    });

                },
                onShowPoster: function () {     //海报生成
                    var imgSrc = $('.poster-head')[0].src;  //头像存在问题
                    $('#poster-pop-up').show();
                    $('html,body').addClass('ovfHiden'); //使网页可滚动
                    initPopupHeight();
                    html2canvas($(".poster-hide-box"), { // $(".myImg")是你要复制生成canvas的区域，可以自己选
                        onrendered: function (canvas) {
                            var dataURL = canvas.toDataURL("image/png");
                            $("#poster_img")[0].src = dataURL;
                        },
                    })
                    $('.poster-hide-box').hide();
                },
            },
            filters: {
                integral: function (value) {
                    return parseInt(value);
                },
                timestampToTime: function (val) {
                    return formatDate(val);
                },
            }
        });

        /**
         * 初始化挑战详情
         */
        function initChallengeDetail() {
            vue.red_envelope_id = parseInt(getQueryString('id'));
            challenge_id = vue.red_envelope_id;
            if (vue.red_envelope_id == null||isNaN(vue.red_envelope_id)) {  //无挑战id
                window.location.href = 'index.html';
            }

            var data = {
                token: token,
                red_envelope_id: vue.red_envelope_id
            }

            $.ajax({
                type: "post"
                , url: '/index/challenge/ajax_challenge_detail'
                , data: data
                , async: false
                , success: function (result) {
                    console.info(result);
                    //if (result.code == -1) {
                    //    layer.msg(result.msg, function () {
                    //        window.location.href = 'index.html';
                    //    });
                    //}
                    if (result.code == 0) {
                        againToken();
                        return;
                    }
                    if (result.code == 1) {
                        vue.challenge_detail = result.data;
                        initDataList();
                    }
                }
                , error: function (resq) {
                    console.info(resq);
                    layer.msg("服务器异常");
                }
            });
        }


        /**
         * 滚动事件
         */
        function scrollFn() {
            //真实内容的高度
            var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight);
            //视窗的高度
            var viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
            //隐藏的高度
            var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

            if (pageHeight - viewportHeight - scrollHeight < 20) {  //如果满足触发条件，执行
                if (vue.next_page <= vue.allpage) {
                    initDataList();
                }
            }
        }

        $('.app-main').bind("scroll", scrollFn);    //绑定滚动事件

        /**
         * 初始化好友答题记录
         */
        function initDataList() {

            var data = {
                token: token,
                red_envelope_id: vue.red_envelope_id,
                page_size: vue.page_size,
                page_num: vue.next_page,
            }
            $.ajax({
                type: "post"
                , url: '/index/challenge/ajax_answer_log'
                , data: data
                , async: false
                , success: function (result) {
                    console.info(result);
                    //if (result.code == -1) {
                    //    layer.msg(result.msg, function () {
                    //        window.location.href = 'index.html';
                    //    });
                    //}
                    if (result.code == 0) {
                        againToken();
                        return;
                    }
                    if (result.code == 1) {
                        if (result.data.page.pagenum == "1") {
                            vue.answer_log_list = result.data.list;
                        } else {
                            vue.answer_log_list.push.apply(vue.answer_log_list, result.data.list);
                        }
                        vue.next_page = parseInt(result.data.page.pagenum) + 1;
                        vue.allpage = result.data.page.totalpage;
                        vue.total_record = result.data.page.totalrecord;
                    }
                }
                , error: function (resq) {
                    console.info(resq);
                    layer.msg("服务器异常");
                }
            });
        }

        /**
         * 二维码初始化
         */
        function initQRcode() {
            var str = toUtf8(BASE_URL + "/pages/answer.html?id=" + vue.red_envelope_id);
            $(".poster-ercode").qrcode({
                render: "canvas", //table方式
                width: 100, //宽度
                height: 100, //高度
                text: str //任意内容
            });
        }

        /**
         * 识别中文
         * @param str
         * @returns {string}
         */
        function toUtf8(str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for (i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                }
            }
            return out;
        }


        initChallengeDetail();
        initQRcode();
    }

    function initPopupHeight() {
        var wH = $('.withdrawal-box').outerHeight();
        $('.withdrawal-box').css('marginTop', (winH - wH) * 0.45 + 'px');

        var pW = $('.poster-box').outerWidth();
        $('.poster-box').height(pW * 1.47 + 'px');

        var pH = $('.poster-box').outerHeight();
        $('.poster-box').css('marginTop', (winH - pH) * 0.35 + 'px');
    };

    //开始答题
    $('#start_answer').click(function () {

    });
    $('.withdrawal-box').click(function (e) {
        e.stopPropagation();
    });

    //开始答题
    $('#poster').click(function () {

    });
    $('.poster-box').click(function (e) {
        e.stopPropagation();
    });

    /**
     * 初始化完成加载函数
     */
    $(function () {
        initGlobalPage();
        initPage();
    })
});


